<?php
/**
 * User: xuanbang.wen
 * Date: 2019/8/29
 */

namespace App\Web\Model;


use App\Web\Facades\UserAuth;
use EchoPHP\Facades\Db;
use Ramsey\Uuid\Uuid;

class ResumeRemark extends Model {
    private $tablename = 'ResumeRemark';

    public function show($resumeId, $myRemark) {
        $sql = 'select r.id as remarkId,c.casename,r.content,u.userid,r.updatedate,u.cname, r.ContactId from ' . $this->tablename . ' as r
                left join User as u on r.creator = u.userid
                left join SCase as c on c.caseid = r.caseid
                where r.resumeid = ? and r.status = ? ';
        $var = [$resumeId, '01'];
        if ($myRemark){
            $sql .= ' and r.creator = ? ';
            $var = array_merge($var,[UserAuth::getLoginId()]);
        }
        $sql.= 'order by r.updatedate desc,id desc';
        return Db::select($sql, $var);
    }

    public function getLatest(array $resumeIds_caseIds, $creator) {
        if (empty($resumeIds_caseIds)) return [];
        /*$sql = "select r.id as remarkId,r.resumeid,r.content,u.userid,r.updatedate,u.cname from " . $this->tablename . " as r
                left join User as u on r.creator = u.userid where id in
                (select max(id) from ResumeRemark where resumeid in (" . substr(str_repeat('?,', count($resumeIds)), 0, -1) . ") and status = '01' group by resumeid)";*/
        $sql = "select caseid,resumeid,content from " . $this->tablename . " where id in 
                (select max(id) from ResumeRemark where CONCAT(resumeid,'_',caseid) in (" . substr(str_repeat('?,', count($resumeIds_caseIds)), 0, -1) . ") 
                and creator=? and status = '01' group by resumeid, caseid)";
        $resumeIds_caseIds[] = $creator;
        return Db::select($sql, $resumeIds_caseIds);
    }

    public function create($params) {
        $sql = 'INSERT INTO ' . $this->tablename . ' (id,resumeid,caseid,content,creator,createdate,updator,updatedate,status)
                value (?,?,?,?,?,NOW(),?,NOW(),?)';
        $var = [
            Uuid::uuid1()->toString(),
            $params['resumeId'],
            $params['caseid'],
            $params['content'],
            $params['userid'],
            $params['userid'],
            '01',
        ];
        return Db::insert($sql, $var);
    }

    public function softDelete($rsmRemarkId) {
        $sql = 'update ' . $this->tablename . ' set status = ?,updatedate = NOW()
        where id = ? and creator = ? and ContactId is null';
        $var = ['06', $rsmRemarkId, UserAuth::getLoginId()];
        return Db::update($sql, $var);
    }

    public function edit($params) {

        $sql = 'update ' . $this->tablename . ' set content = ?,updator = ?,updatedate =NOW()
                where id = ? and creator = ?';
        $var = [$params['content'], $params['userid'], $params['remarkId'], $params['userid']];
        return Db::update($sql, $var);
    }
}